//
//  PhotoBrowerCell.swift
//  Weibo8023
//
//  Created by styshy on 15/12/20.
//  Copyright © 2015年 sz. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

// 自定义代理
protocol PhotoBrowserCellDelegate:NSObjectProtocol{
    func photoBrowserCellDidTapImage()
}

class PhotoBrowerCell: UICollectionViewCell {
    
    weak var photoDelegate: PhotoBrowserCellDelegate?
    
    // 监听方法
    @objc private func tapImage(){
        photoDelegate?.photoBrowserCellDidTapImage()
    }
    
    // 属性可以被外界访问，并且赋值
    var imageUrl:NSURL?{
        didSet{
            guard let url = imageUrl else{
                return
            }
            // 重置scrollView
            resetScrollView()
            // Question:没有先显示缩略图 首先显示缩略图
            let placeHolderImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url.absoluteString)
            
            setPlaceHolder(placeHolderImage)
            placeHolder.setNeedsDisplay()
            
            imgView.sd_setImageWithURL(bmiddle(url),
                placeholderImage: nil,
                options: [SDWebImageOptions.RefreshCached,SDWebImageOptions.RetryFailed],
                progress: { (current, total) -> Void in

                    // 主线程上跟新UI
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.placeHolder.progress = CGFloat(current)/CGFloat(total)
                    })
                    
                }) { (image, _, _, _) -> Void in
                    
                    // 判断图片下载是否成功
                    guard let image = image else{
                        SVProgressHUD.showInfoWithStatus("您的网络不给力")
                        return
                    }
                    
                    self.placeHolder.hidden = true
                    
                    self.setPostion(image)
            }

        }
    }
    
    private func setPlaceHolder(image:UIImage){
        placeHolder.hidden = false
        
        placeHolder.image = image
        placeHolder.sizeToFit()
        placeHolder.center = scrollView.center
    }
    
    // 重置scrollView
    private func resetScrollView(){
        scrollView.transform = CGAffineTransformIdentity
        
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    /**
     设置图片位置
     
     - parameter image: UIImage
     */
    private func setPostion(image:UIImage){
        let sw = UIScreen.mainScreen().bounds.width
        let sh = UIScreen.mainScreen().bounds.height
        
        
        let imageHeight = (image.size.height * sw) / image.size.width
        // 计算y的坐标
        let imageY = imageHeight > sh ? 0 : (sh-imageHeight) * 0.5
        
        
        imgView.frame = CGRect(x: 0, y: imageY, width: sw, height: imageHeight)
//        if imageHeight > sh{
//            
//            scrollView.contentSize = CGSize(width: sw, height: imageHeight)
//        }else{
//            scrollView.contentInset = UIEdgeInsets(top: imageY, left: 0, bottom: 0, right: 0)
//        }
    }
    
    
    // 返回中等尺寸的图片
    private func bmiddle(url:NSURL) -> NSURL{
        // 转换成string
        var urlString = url.absoluteString
        // 替换路径
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        // 返回url
        return NSURL(string: urlString)!
    }
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var imgView = UIImageView()
    
    lazy var scrollView = UIScrollView()
    
    private lazy var placeHolder:ProgressImageView = ProgressImageView()
    
}


// MARK: - 布局设置
extension PhotoBrowerCell{
    private func setupUI(){
        contentView.addSubview(scrollView)
        scrollView.addSubview(imgView)
        scrollView.addSubview(placeHolder)

        
        // 设置位置
        var rect = bounds
        rect.size.width -= 20
        
        scrollView.frame = rect
//        print(rect)
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        
        // 4.添加手势识别
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        // 图片默认是无法跟用户交互的，代码代开之后可以获取点击事件
        imgView.userInteractionEnabled = true
        imgView.addGestureRecognizer(tap)
    }
}

extension PhotoBrowerCell:UIScrollViewDelegate{
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imgView
    }
    
    func scrollViewDidZoom(scrollView: UIScrollView) {
        print("imgView =  \(imgView.transform)")
    }
    
    // 缩放完成之后放到中间位置
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        var offSetX:CGFloat = (scrollView.bounds.width - view!.frame.width) * 0.5
        offSetX = offSetX > 0 ? offSetX : 0
        var offSetY:CGFloat = (scrollView.bounds.height - view!.frame.height) * 0.5
        offSetY = offSetY > 0 ? offSetY : 0
        
        scrollView.contentInset = UIEdgeInsets(top: offSetY, left: offSetX, bottom: 0, right: 0)
    }
}
